#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <string.h>

// 事件类型定义
typedef enum {
    EVENT_NONE = 0,
    EVENT_TIMER,// 定时事件 1
    EVENT_KEY_INPUT,// 按键输入事件 2
    EVENT_NETWORK,// 网络事件 3
    EVENT_SENSOR,// 传感器事件 4
    EVENT_USER_DEFINED
} EventType;

// 事件结构体
typedef struct {
    EventType type;
    int id;
    void* data;
    size_t data_len;
    unsigned long timestamp;
} Event;

// 事件队列节点
typedef struct EventNode {
    Event event;
    struct EventNode* next;
} EventNode;

// 事件队列
typedef struct {
    EventNode* front;
    EventNode* rear;
    pthread_mutex_t mutex;
    pthread_cond_t cond;
    int count;
    int max_size;
} EventQueue;

// 任务函数指针类型
typedef void (*TaskHandler)(Event event);

// 任务注册表
typedef struct {
    EventType type;
    TaskHandler handler;
    char task_name[32];
} TaskRegistry;

// 全局变量
static pthread_t g_thread0;
static pthread_t g_thread1;
static pthread_t g_thread2;
static EventQueue g_event_queue;
static TaskRegistry g_task_registry[10];
static int g_registry_count = 0;

// 事件队列初始化
int event_queue_init(EventQueue* queue, int max_size) {
    queue->front = queue->rear = NULL;
    queue->count = 0;
    queue->max_size = max_size;
    pthread_mutex_init(&queue->mutex, NULL);
    pthread_cond_init(&queue->cond, NULL);
    return 0;
}

// 事件队列销毁
void event_queue_destroy(EventQueue* queue) {
    pthread_mutex_lock(&queue->mutex);
    
    EventNode* current = queue->front;
    while (current != NULL) {
        EventNode* next = current->next;
        if (current->event.data != NULL) {
            free(current->event.data);
        }
        free(current);
        current = next;
    }
    
    queue->front = queue->rear = NULL;
    queue->count = 0;
    pthread_mutex_unlock(&queue->mutex);
    
    pthread_mutex_destroy(&queue->mutex);
    pthread_cond_destroy(&queue->cond);
}

// 向事件队列添加事件
int event_queue_push(EventQueue* queue, Event event) {
    pthread_mutex_lock(&queue->mutex);
    
    if (queue->count >= queue->max_size) {
        pthread_mutex_unlock(&queue->mutex);
        printf("Event queue is full!\n");
        return -1;
    }
    
    EventNode* new_node = (EventNode*)malloc(sizeof(EventNode));
    if (!new_node) {
        pthread_mutex_unlock(&queue->mutex);
        return -1;
    }
    
    // 复制事件数据
    new_node->event = event;
    if (event.data != NULL && event.data_len > 0) {
        new_node->event.data = malloc(event.data_len);
        if (new_node->event.data) {
            memcpy(new_node->event.data, event.data, event.data_len);
        }
    }
    
    new_node->next = NULL;
    
    if (queue->rear == NULL) {
        queue->front = queue->rear = new_node;
    } else {
        queue->rear->next = new_node;
        queue->rear = new_node;
    }
    
    queue->count++;
    pthread_cond_signal(&queue->cond);
    pthread_mutex_unlock(&queue->mutex);
    
    return 0;
}

// 从事件队列获取事件
int event_queue_pop(EventQueue* queue, Event* event) {
    pthread_mutex_lock(&queue->mutex);
    
    while (queue->front == NULL) {
        pthread_cond_wait(&queue->cond, &queue->mutex);
    }
    
    EventNode* temp = queue->front;
    *event = temp->event;
    
    queue->front = queue->front->next;
    if (queue->front == NULL) {
        queue->rear = NULL;
    }
    
    queue->count--;
    free(temp);
    pthread_mutex_unlock(&queue->mutex);
    
    return 0;
}

// 获取事件队列大小
int event_queue_size(EventQueue* queue) {
    pthread_mutex_lock(&queue->mutex);
    int size = queue->count;
    pthread_mutex_unlock(&queue->mutex);
    return size;
}

// 注册任务处理器
void register_task_handler(EventType type, TaskHandler handler, const char* name) {
    if (g_registry_count < 10) {
        g_task_registry[g_registry_count].type = type;
        g_task_registry[g_registry_count].handler = handler;
        strncpy(g_task_registry[g_registry_count].task_name, name, 31);
        g_registry_count++;
        printf("Registered handler for event type %d: %s\n", type, name);
    }
}

// 查找任务处理器
TaskHandler find_task_handler(EventType type) {
    for (int i = 0; i < g_registry_count; i++) {
        if (g_task_registry[i].type == type) {
            return g_task_registry[i].handler;
        }
    }
    return NULL;
}

// 事件调度器 - 核心调度逻辑
void* os_scheduler(void* arg) {
    printf("Scheduler started\n");
    
    while (1) {
        Event event;
        if (event_queue_pop(&g_event_queue, &event) == 0) {
            printf("\n[Scheduler] Processing event: type=%d, id=%d\n", event.type, event.id);
            
            // 查找对应的任务处理器
            TaskHandler handler = find_task_handler(event.type);
            if (handler != NULL) {
                handler(event);
            } else {
                printf("[Scheduler] No handler for event type %d\n", event.type);
            }
            
            // 清理事件数据
            if (event.data != NULL) {
                free(event.data);
            }
        }
        
        usleep(100000); // 100ms 调度间隔
    }
    
    return NULL;
}

// 事件输入任务 - 模拟事件产生
void* EveInTask(void* arg) {
    printf("Event input task started\n");
    int event_id = 0;
    
    while (1) {
        // 模拟不同类型的事件产生
        EventType types[] = {EVENT_TIMER, EVENT_KEY_INPUT, EVENT_NETWORK, EVENT_SENSOR};
        EventType random_type = types[event_id % 4];
        
        Event event;
        event.type = random_type;
        event.id = event_id++;
        event.timestamp = (unsigned long)time(NULL);
        
        // 为某些事件添加数据
        if (random_type == EVENT_NETWORK) {
            char* msg = "Network packet data";
            event.data_len = strlen(msg) + 1;
            event.data = msg;
        } else if (random_type == EVENT_SENSOR) {
            int sensor_data = rand() % 100;
            event.data_len = sizeof(int);
            event.data = &sensor_data;
        } else {
            event.data = NULL;
            event.data_len = 0;
        }
        
        if (event_queue_push(&g_event_queue, event) == 0) {
            printf("[Input] Generated event: type=%d, id=%d\n", event.type, event.id);
        }
        
        sleep(2); // 每2秒产生一个事件
    }
    
    return NULL;
}

// 事件处理任务0
void* EveTask0(void* arg) {
    printf("Event task 0 started\n");
    
    // 注册定时器事件处理器
    // register_task_handler(EVENT_TIMER, EveTask0, "TimerEventHandler");
    
    while (1) {
        // 这个任务现在通过事件驱动方式被调用
        sleep(1);
    }
    
    return NULL;
}

// 事件处理任务1
void* EveTask1(void* arg) {
    printf("Event task 1 started\n");
    
    // 注册键盘输入和网络事件处理器
    // register_task_handler(EVENT_KEY_INPUT, EveTask1, "KeyInputHandler");
    // register_task_handler(EVENT_NETWORK, EveTask1, "NetworkHandler");
    
    while (1) {
        // 这个任务现在通过事件驱动方式被调用
        sleep(1);
    }
    
    return NULL;
}

// 定时器事件处理函数
void timer_event_handler(Event event) {
    printf("[Task0-Timer] Handling timer event %d at timestamp %lu\n", 
           event.id, event.timestamp);
    
    // 模拟定时器任务处理
    printf("[Task0-Timer] Performing periodic task...\n");
}

// 键盘输入事件处理函数  
void key_input_handler(Event event) {
    printf("[Task1-KeyInput] Handling key input event %d\n", event.id);
    
    // 模拟键盘输入处理
    printf("[Task1-KeyInput] Processing user input...\n");
}

// 网络事件处理函数
void network_event_handler(Event event) {
    printf("[Task1-Network] Handling network event %d\n", event.id);
    
    if (event.data != NULL) {
        printf("[Task1-Network] Received data: %s\n", (char*)event.data);
    }
    
    // 模拟网络数据处理
    printf("[Task1-Network] Processing network packet...\n");
}

// 传感器事件处理函数
void sensor_event_handler(Event event) {
    printf("[Sensor] Handling sensor event %d\n", event.id);
    
    if (event.data != NULL) {
        int sensor_value = *(int*)event.data;
        printf("[Sensor] Sensor value: %d\n", sensor_value);
        
        // 模拟传感器数据处理
        if (sensor_value > 50) {
            printf("[Sensor] High value detected! Taking action...\n");
        }
    }
}

int main(void) {
    printf("Starting Event-Driven System...\n");
    
    // 初始化事件队列
    if (event_queue_init(&g_event_queue, 100) != 0) {
        printf("Failed to initialize event queue\n");
        return -1;
    }
    
    // 注册事件处理器
    register_task_handler(EVENT_TIMER, timer_event_handler, "TimerHandler");
    register_task_handler(EVENT_KEY_INPUT, key_input_handler, "KeyInputHandler");
    register_task_handler(EVENT_NETWORK, network_event_handler, "NetworkHandler");
    register_task_handler(EVENT_SENSOR, sensor_event_handler, "SensorHandler");
    
    // 创建线程
    pthread_create(&g_thread0, NULL, os_scheduler, NULL);
    pthread_create(&g_thread1, NULL, EveInTask, NULL);
    // pthread_create(&g_thread2, NULL, EveTask0, NULL);
    
    printf("Event-driven system started successfully\n");
    printf("Queue size: %d\n", event_queue_size(&g_event_queue));
    
    // 主线程等待所有子线程
    pthread_join(g_thread0, NULL);
    pthread_join(g_thread1, NULL);
    pthread_join(g_thread2, NULL);
    
    // 清理资源
    event_queue_destroy(&g_event_queue);
    
    return 0;
}